package com.fakoua;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.*;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

import java.io.*;
import java.text.BreakIterator;
import java.util.jar.Attributes;

public class MyActivity extends Activity
{
        protected EditText searchText;
        protected SQLiteDatabase db;
        protected Cursor cursor;
        protected ListAdapter adapter;
        protected ListView employeeList;
        protected TextView txtCount;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        db = (new com.fakoua.DatabaseHelper(this)).getWritableDatabase();
        searchText = (EditText) findViewById (R.id.searchText);
        txtCount = (TextView) findViewById(R.id.count );
        employeeList = (ListView) findViewById (R.id.list);

        employeeList.setOnItemClickListener(new AdapterView.OnItemClickListener()
         {
              public void onItemClick(AdapterView arg0, View arg1,int pos, long arg3)
              {
                  cursor.moveToPosition(pos);
                  //Msg( cursor.getString(1) + "  " + cursor.getString(0));
                   showContactAction(cursor);

              }
         });


         final ImageButton button = (ImageButton) findViewById(R.id.searchButton);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click
                 search();
                 InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                 mgr.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
             }
         });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item) {
        String mItem = "" + item.getTitle();
        if (mItem.equalsIgnoreCase("Exit") ) {
           Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        else {
           showAbout();
        }
        return true;
    }

    public void search() {
       try {
             cursor = db.rawQuery("SELECT _id, name, phone FROM phonebook WHERE name LIKE ? OR phone LIKE ?",
                                                new String[]{"%" + searchText.getText().toString() + "%", "%" + searchText.getText().toString() + "%"});
                adapter = new SimpleCursorAdapter(
                                this,
                                R.layout.oneitem,
                                cursor,
                                new String[] {"name", "phone"},
                                new int[] {R.id.name, R.id.phone });
                employeeList.setAdapter(adapter);
                txtCount.setText( "Results found: " + cursor.getCount()  );
       }
       catch (Exception e) {
            Msg(e.getMessage() );
       }

    }

    public void Msg(String M) {

         AlertDialog alertDialog;
                        alertDialog = new AlertDialog.Builder(MyActivity.this).create();
                        alertDialog.setTitle("Packing List");
                        alertDialog.setMessage(M);
                        alertDialog.show();
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

    private void showContactAction(Cursor c) {
          final String contactName = c.getString(1);
          final String phoneNumber = c.getString(2);
          final Number _id = c.getLong(0);

         final Dialog dlg = new Dialog(MyActivity.this);
          dlg.setContentView(R.layout.contactaction );
          dlg.setTitle("Contact Action");
          //dlg.setCancelable(true);
          TextView txtContactName = (TextView) dlg.findViewById(R.id.contactName );
        txtContactName.setText(contactName);

        ListView lstAction = (ListView ) dlg.findViewById(R.id.listAction );
        String lv_arr[]={"Dial","Send SMS","Import to contacts","Close"};
        lstAction.setAdapter(new ArrayAdapter<String>(this,R.layout.itemaction , lv_arr));

         lstAction.setOnItemClickListener(new AdapterView.OnItemClickListener()
         {
              public void onItemClick(AdapterView av, View v,int pos, long arg3)
              {
                  switch ( pos) {
                    case 0:
                        call(phoneNumber);
                        break;
                    case 1:
                        sendSMS(phoneNumber);
                        break;
                    case 2:
                        importContact(contactName, phoneNumber, _id);
                        break;
                    default:
                        dlg.cancel();
                    }
              }
         });
        /*

            Button btnDial = (Button) dlg.findViewById(R.id.btnDial);
            btnDial.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    call(phoneNumber);
                }
            });

            Button btnSms = (Button) dlg.findViewById(R.id.btnSms);
            btnSms.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    sendSMS(phoneNumber);
                }
            });

        Button btnImport = (Button) dlg.findViewById(R.id.btnImport );
        btnImport.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                importContact(contactName, phoneNumber, _id);
            }
        } );

         */
          dlg.show();

    }

    private void call(String phoneNumber) {
        try {
           startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)));
        } catch (ActivityNotFoundException e) {
            Log.e("com.fakoua dialing", "Call failed", e);
        }
    }

    private void sendSMS(String phoneNumber) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phoneNumber, null)));
    }

    private void importContact(String name, String phoneNumber, Number _id) {
          Intent i=new Intent(Intent.ACTION_INSERT_OR_EDIT);
            i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
            i.putExtra(ContactsContract.Intents.Insert.NAME, name );
            i.putExtra(ContactsContract.Intents.Insert.PHONE , phoneNumber ) ;
            startActivity(i);

            Toast toast=Toast.makeText(this, "Click: Create new contact", 2000);
            toast.setGravity(Gravity.CENTER, -30, 50);
            toast.show();
    }

    private void showAbout() {
       Dialog dlg = new Dialog(MyActivity.this);
       dlg.setContentView(R.layout.about );
       dlg.setTitle("About");
        dlg.show();
    }



}
